<template>
  <view :class="['ai-message-card', role]">
    <image
      v-if="role === 'assistant'"
      class="avatar"
      src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
      mode="aspectFill"
    />
    <view class="message-wrap" v-if="message.text">
      <view class="message-time">{{ formatTime(message.time) }}</view>
      <view class="message">{{ message.text }}</view>
      <view class="message-bottom" v-if="role === 'assistant'">
        <ai-button text="币种分析" size="mini" @click="handleButtonClick('币种分析')"></ai-button>
        <ai-button text="解锁高级服务" size="mini" @click="handleButtonClick('解锁高级服务')"></ai-button>
      </view>
    </view>

    <view class="loader" v-else>
      <view class="dot"></view>
      <view class="dot"></view>
      <view class="dot"></view>
    </view>
  </view>
</template>

<script>
import AiButton from './ai-button.vue'
import dayjs from 'dayjs'

export default {
  name: 'AiMessage',
  components: {
    AiButton
  },
  props: {
    role: {
      type: String,
      required: true,
      validator: (value) => ['user', 'assistant'].includes(value)
    },
    message: {
      type: Object,
      default: () => ({})
    }
  },
  methods: {
    formatTime(timestamp) {
      if (!timestamp) return ''
      return dayjs(timestamp).format('YYYY年MM月DD日 HH:mm')
    },
    handleButtonClick(action) {
      this.$emit('button-click', action)
    }
  }
}
</script>

<style lang="scss" scoped>
@keyframes dot-flashing {
  0% {
    opacity: 0.4;
  }
  50% {
    opacity: 1.0;
  }
  100% {
    opacity: 0.4;
  }
}

.loader {
  display: flex;
  align-items: center;
  height: 52rpx;
  margin-left: 8rpx;

  .dot {
    display: inline-block;
    animation: dot-flashing 1.2s infinite ease-in-out both;
    background: #333;
    width: 10rpx;
    height: 10rpx;
    border-radius: 50%;
    margin: 0 4rpx;

    &:nth-child(2) {
      animation-delay: 0.4s;
    }

    &:nth-child(3) {
      animation-delay: 0.8s;
    }
  }
}

.ai-message-card {
  display: flex;
  align-items: flex-start;
  margin-bottom: 64rpx;

  .avatar {
    width: 52rpx;
    height: 52rpx;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .message {
    padding: 24rpx;
    color: #495057;
    background: #F8F9FA;
    font-size: 28rpx;
    line-height: 40rpx;
    border-radius: 16rpx;
    margin-top: 16rpx;
  }

  &.user {
    justify-content: flex-end;

    .message-wrap {
      margin-left: 0;
      align-items: flex-end;
    }

    .message {
      background: #05cab6;
      color: #fff;
    }
  }

  .message-wrap {
    display: flex;
    flex-direction: column;
    margin-left: 16rpx;
    max-width: calc(100vw - 200rpx);

    .message-time {
      font-size: 24rpx;
      line-height: 36rpx;
      color: #999;
    }

    .message-bottom {
      margin-top: 16rpx;
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style>
